import 'package:flutter/material.dart';

/// 数据模型
class MultiSelectItem<T> {
  final T value; // 实际业务数据
  final String label; // 展示文本
  bool selected;

  MultiSelectItem(this.value, this.label, {this.selected = false});
}

/// 多选弹窗
class MultiSelectDialog<T> extends StatefulWidget {
  final String? title;
  final List<MultiSelectItem<T>> items;
  final int maxSelect;
  final int minSelect;
  final void Function(List<T> selected)? onConfirm;
  final VoidCallback? onCancel;

  const MultiSelectDialog({
    Key? key,
    this.title,
    required this.items,
    this.maxSelect = 999,
    this.minSelect = 0,
    this.onConfirm,
    this.onCancel,
  }) : super(key: key);

  /// 链式快速弹出
  static Future<List<T>?> show<T>({
    required BuildContext context,
    String? title,
    required List<T> data,
    required String Function(T) labelBuilder,
    List<T> defaultSelected = const [],
    int maxSelect = 999,
    int minSelect = 0,
  }) async {
    final items = data
        .map((e) => MultiSelectItem<T>(
              e,
              labelBuilder(e),
              selected: defaultSelected.contains(e),
            ))
        .toList();

    return showDialog<List<T>>(
      context: context,
      builder: (_) => MultiSelectDialog<T>(
        title: title,
        items: items,
        maxSelect: maxSelect,
        minSelect: minSelect,
        onConfirm: (list) => Navigator.of(context).pop(list),
        onCancel: () => Navigator.of(context).pop(),
      ),
    );
  }

  @override
  State<MultiSelectDialog<T>> createState() => _MultiSelectDialogState<T>();
}

class _MultiSelectDialogState<T> extends State<MultiSelectDialog<T>> {
  late List<MultiSelectItem<T>> _items;

  @override
  void initState() {
    super.initState();
    _items = List.of(widget.items);
  }

  bool get _canConfirm {
    final count = _items.where((e) => e.selected).length;
    return count >= widget.minSelect && count <= widget.maxSelect;
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: widget.title == null ? null : Text(widget.title!),
      content: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: _items.map((item) {
            return CheckboxListTile(
              title: Text(item.label),
              value: item.selected,
              onChanged: (val) {
                if (val == true && _items.where((e) => e.selected).length >= widget.maxSelect) {
                  return; // 已达上限
                }
                setState(() => item.selected = val!);
              },
            );
          }).toList(),
        ),
      ),
      actions: [
        TextButton(onPressed: widget.onCancel, child: const Text('取消')),
        ElevatedButton(
          onPressed: _canConfirm
              ? () {
                  final selected = _items.where((e) => e.selected).map((e) => e.value).toList();
                  widget.onConfirm?.call(selected);
                }
              : null,
          child: const Text('确定'),
        ),
      ],
    );
  }
}
